const Router = require("@koa/router");
const { Pool } = require("pg");
const router = new Router({ prefix: "/users" });
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });

// 配置数据库连接池
const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_DATABASE,
  password: process.env.DB_PASSWORD,
  port: process.env.DB_PORT,
});

// 获取用户列表
router.get("/", async (ctx) => {
  try {
    const result = await pool.query("SELECT * FROM user");
    ctx.body = { success: true, data: result.rows };
  } catch (err) {
    console.error(`${new Date().toLocaleString()} 获取用户列表失败:`, err);
    ctx.status = 500;
    ctx.body = { success: false, message: err.message };
  }
});

// 保存Google用户信息到数据库
const saveUserToDatabase = async (googleUser) => {
  try {
    // 首先检查用户是否已存在
    const existingUser = await pool.query(
      "SELECT * FROM users WHERE email = $1",
      [googleUser.email]
    );

    if (existingUser.rows.length > 0) {
      // 用户已存在，更新用户信息
      const updateResult = await pool.query(
        "UPDATE users SET nickname = $1, avatar = $2 WHERE email = $3 RETURNING *",
        [googleUser.name, googleUser.picture, googleUser.email]
      );
      console.log(`${new Date().toLocaleString()} 用户信息已更新:`, updateResult.rows[0]);
      return updateResult.rows[0];
    } else {
      // 用户不存在，创建新用户
      // 获取最大ID并加1
      const maxIdResult = await pool.query("SELECT COALESCE(MAX(id), 0) + 1 as next_id FROM users");
      const nextId = maxIdResult.rows[0].next_id;
      
      const insertResult = await pool.query(
        "INSERT INTO users (id, email, nickname, avatar, created_at) VALUES ($1, $2, $3, $4, $5) RETURNING *",
        [nextId, googleUser.email, googleUser.name, googleUser.picture, new Date().toISOString().split('T')[0]]
      );
      console.log(`${new Date().toLocaleString()} 新用户已创建:`, insertResult.rows[0]);
      return insertResult.rows[0];
    }
  } catch (err) {
    console.error(`${new Date().toLocaleString()} 保存用户信息失败:`, err);
    throw new Error('Failed to save user to database');
  }
};

module.exports = { router, saveUserToDatabase };
